from flask import redirect, url_for, Blueprint, flash, render_template
from flask_login import current_user, login_user, logout_user, login_required

from FileShare.forms import RegisterForm, LoginForm
from FileShare.models import User
from FileShare.extensions import db

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))
    form = RegisterForm()
    if form.validate_on_submit():
        username = form.username.data
        email = form.email.data.lower()
        password = form.password.data

        user = User(username=username, email=email)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()

        flash('注册成功')
        return redirect(url_for('.login'))
    return render_template('auth/register.html', form=form)

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('main.index'))

    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if (user is not None) and user.validate_password(form.password.data):
            if login_user(user, form.remember.data):
                flash('Login success.', 'info')
                return redirect(url_for('main.index'))
            else:
                flash('Your account is blocked.', 'warning')
                return redirect(url_for('.login'))
        flash('Invalid email or password.', 'warning')

    return render_template('auth/login.html', form=form)

@auth_bp.route('/logout')
@login_required    # 如果本身没有登陆就会跳转到登陆界面
def logout():
    logout_user()    # 清理session，清理后会跳转到url_for('.login')
    flash('Logout success.', 'info')
    return redirect(url_for('.login'))